package com.fly.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.SystemUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class CmdExecutor
{
    /**
     * execute命令
     * 
     * @param command
     * @param printResult 是否打印结果
     * @throws IOException
     */
    public static void execute(String command, boolean printResult)
    {
        try
        {
            log.info("✈✈✈✈✈ WILL EXECUTE COMMAND: {} ✈✈✈✈✈", command);
            String[] cmd = SystemUtils.IS_OS_WINDOWS ? new String[] {"cmd", "/c", command} : new String[] {"/bin/sh", "-c", command};
            if (!printResult)
            {
                Runtime.getRuntime().exec(cmd);
                return;
            }
            List<String> resultList = new ArrayList<>();
            Process ps = Runtime.getRuntime().exec(cmd);
            try (BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream())))
            {
                String line;
                while ((line = br.readLine()) != null)
                {
                    resultList.add(line);
                }
            }
            resultList.stream().forEach(log::info);
        }
        catch (IOException e)
        {
            log.error(e.getMessage(), e);
        }
    }
}
